﻿<%@ WebHandler Language="C#" Class="RbContainerStartHandler" %>

using System;
using System.Web;
using System.Collections.Generic;
using System.Web.Script.Serialization;
using System.Linq;
using BusinessRule.Business;
using System.Data;
using Newtonsoft.Json;
using System.IO;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using NPOI.HSSF.UserModel;
using System.Collections;
using BusinessRule.DTO;
using BusinessRule.IBusiness;
using BusinessRule.BusinessFactory;
using System.Web.SessionState;
using Camstar.WebClient.WebServicesProxy.InSiteWebServices;
using DatabaseAccess.DBUtility;



public class RbContainerStartHandler : IHttpHandler, IRequiresSessionState
{
    private uLMSCommonIBusiness m_CommonObj = uMESBusinessFactory.instance.GetuLMSCommonObject();
    private RbContainerBusiness m_RbContianer = new RbContainerBusiness();
    private uLMSContainerIBusiness m_ContainerObj = uMESBusinessFactory.instance.GetuLMSContainerObject();
    private static object thisLock = new object();
    CurrentUserInfo m_UserInfo;

    public void ProcessRequest(HttpContext context)
    {
        try
        {
            m_UserInfo = (CurrentUserInfo)context.Session["CurrentUserInfo"];
            var action = context.Request["action"].ToString();
            switch (action)
            {
                case "intiPageData":
                    IntiPageData(context);
                    break;
                case "getNewestContainerNo":
                    GetNewestContainerNo(context);
                    break;
                case "getNewestContainerNo2":
                    GetNewestContainerNo2(context);
                    break;
                case "GetRBChildWorkflow": //获取热表子工艺，转工工序下拉改变 add by zhangrj 2022-10-25
                    GetRBChildWorkflow(context);
                    break;
                case "startContainer":
                    lock (thisLock)
                    {
                        StartContainer(context);
                    }
                    break;
                case "getCreatedRbContianer":
                    GetCreatedRbContianer(context);
                    break;
                case "123":
                    context.Response.ContentType = "text/plain";
                    context.Response.Write(@"[{""id"":1,""text"":""text1""},{""id"":2,""text"":""text2""}]");
                    break;
                default:
                    context.Response.ContentType = "text/plain";
                    context.Response.Write(@"{""Result"":false,""Message"":""" + "无传入action" + @"""}");
                    break;
            }
        }
        catch (Exception e)
        {
            context.Response.Write(@"{""Result"":false,""Message"":""" + e.Message + @"""}");
        }
    }
    public bool IsReusable
    {
        get
        {
            return false;
        }
    }

    /// <summary>
    /// 获取工序的热表子工艺 add by zhangrj 2022-10-25
    /// </summary>
    /// <param name="context"></param>
    public void GetRBChildWorkflow(HttpContext context)
    {
        //针对多工序转工，只能开当前工序的子工艺流卡的情况 add by zhangrj 2022-10-20
        string workflowStepID = context.Request["workflowstepid"].ToString();
        string containerType = context.Request["containerType"].ToString();
        string containerID = context.Request["containerID"].ToString();
        string subProductInfo = context.Request["subProductInfo"].ToString();
        uMESProcessResult result = new uMESProcessResult();
        Dictionary<string, object> returnData = new Dictionary<string, object>();
        //查询机加工序的子工艺信息（热表工艺）
        DataTable subWorkflowDt = m_CommonObj.GetSubWorkflowInfo(new Dictionary<string, string> { { "WorkflowStepID", workflowStepID }, { "FactoryID", m_UserInfo.FactoryID } });
        //处理机加工序的子工艺信息（热表工艺）
        if (subWorkflowDt.Rows.Count > 0)
        {
            returnData["SubWorkflowId"] = subWorkflowDt.Rows[0]["subworkflowid"].ToString();
            returnData["SubWorkflowInfo"] = subWorkflowDt.Rows[0]["subworkflowname"].ToString() + ":" + subWorkflowDt.Rows[0]["subworkflowrevision"].ToString();
            DataTable subProductDt = m_CommonObj.GetProductInfoByID(subWorkflowDt.Rows[0]["subproductid"].ToString());
            if (subProductDt.Rows.Count > 0)
            {
                returnData["SubProductInfo"] = subProductDt.Rows[0]["PRODUCTNAME"].ToString() + ":" + subProductDt.Rows[0]["productrevision"].ToString();
            }

            //查询子工艺关联的子件号,可能一对多，系统处理，和主件号匹配 add:Wangjh 2023/2/20
            subProductDt = DatabaseHelper.Query_ReturnDatTable(string.Format(@"select pw.workflowid,pb.productname,p.productrevision from productworkflowmapping pw
left join product p on p.productid=pw.productid
left join productbase pb on pb.productbaseid=p.productbaseid
where pw.workflowid='{0}'", subWorkflowDt.Rows[0]["subworkflowid"].ToString()));
            if (subProductDt.Rows.Count > 0)
            {
                var subProduct = subProductDt.Select("productname = '" + subProductInfo.Split(':')[0] + "'");
                if (subProduct.Length > 0)
                {
                    returnData["SubProductInfo"] = subProduct[0]["PRODUCTNAME"].ToString() + ":" + subProduct[0]["productrevision"].ToString();
                }
            }

            //查询子工艺最新的工艺 add:Wangjh 20230322
            var newestSubWorkflow = m_CommonObj.GetWorkflowInfoByNameAndRev(new Dictionary<string, string>(){
                {"WorkflowName",subWorkflowDt.Rows[0]["subworkflowname"].ToString()}
            }).AsEnumerable().OrderByDescending(row => row["workflowid"].ToString()).FirstOrDefault();

            returnData["NewestSubWorkflowRev"] = newestSubWorkflow["workflowrevision"].ToString();

        }
        if (containerType == "3")//如果是批量带子序号，则要更新子序号列表
        {
            DataTable dtChildContainer = new DataTable();
            dtChildContainer = m_RbContianer.GetChildContainer(containerID, workflowStepID);
            dtChildContainer.TableName = "ChildContainer";
            result.DBTable = dtChildContainer;
        }

        returnData.Add("StepPlannedStartDate", GetStepPlannedStartDate(containerID, workflowStepID));

        result.ReturnData = returnData;
        result.Result = true;
        context.Response.Write(JsonConvert.SerializeObject(result));
    }

    /// <summary>
    /// 批次创建
    /// </summary>
    /// <param name="context"></param>
    public void StartContainer(HttpContext context)
    {
        context.Response.ContentType = "text/plain";
        uMESProcessResult result = new uMESProcessResult();
        result.Result = true;

        if (context.Request["containers"] == null)
        {
            result.Result = false;
            result.Message = "无批次信息";
            context.Response.Write(JsonConvert.SerializeObject(result));
            return;
        }

        DataTable containers = JsonConvert.DeserializeObject<DataTable>(context.Request["containers"]);
        foreach (DataRow item in containers.Rows)
        {
            if (m_RbContianer.IsExistsSubContainer(item["FATHERCONTAINERID"].ToString(), item["FAWORKFLOWSTEPNAME"].ToString()))
            {
                result.Result = false;
                result.Message = "批次已存在子卡";
                break;
            }
        }
        if (!result.Result)
        {
            context.Response.Write(JsonConvert.SerializeObject(result));
            return;
        }

        var con = containers.Rows[0];

        //查询最大批次号
        int maxIndex = m_RbContianer.GetNewestContainerNo(con["PRODUCTNAME"].ToString() + "/" + con["RbTogetherflag"].ToString() + "-");
        string containerNo = con["RbTogetherflag"] + "-" + (++maxIndex).ToString("D2");
        if (con["CONTAINERNO"].ToString() != containerNo)
        {
            result.Result = false;
            result.Message = "批次号已更新，请刷新页面";
            context.Response.Write(JsonConvert.SerializeObject(result));
            return;
        }

        //已选择的子序号
        var childContainer = JsonConvert.DeserializeObject<DataTable>(context.Request["childContainer"]);

        var beginStep = "";
        //如果有热表工艺，则默认为第一个序
        var workflowStepDt = m_CommonObj.GetWorkFlowSetpsByWorkflowID(con["WORKFLOWID"].ToString());
        if (workflowStepDt.Rows.Count > 0)
        {
            beginStep = workflowStepDt.Rows[0]["WORKFLOWSTEPNAME"].ToString();
            string strsql = "SELECT 1 FROM workflowstep w WHERE w.workflowstepid = '" + con["FAWORKFLOWSTEPID"].ToString() + "' AND w.wipmsglabel = '子工艺'";
            if (DatabaseHelper.Query_ReturnDatTable(strsql).Rows.Count == 0)
            {
                result.Result = false;
                result.Message = "转工工序没有定义子工艺";
                context.Response.Write(JsonConvert.SerializeObject(result));
                return;
            }
        }

        //批次创建
        //获取此次开卡所有相关的FATOGETHERFLAG
        string faTogetherFlags = "";
        var faTogetherFlagDt = m_RbContianer.GetRelativesFatogetherflag(con["FATOGATHERFLAG"].ToString());
        foreach (DataRow r in faTogetherFlagDt.Rows)
        {
            faTogetherFlags += "'" + r["faTogetherFlag"].ToString() + "',";
        }
        faTogetherFlags = faTogetherFlags.TrimEnd(',');
        if (con["RbTogetherflagType"].ToString() == "0") //如果是最新获取的热表大批次，则要验证
        {
            //验证rbtogetherflag防止重复,一个父TOGATHERFLAG和RbContainerType对应一个RbTogetherflag
            var strSql = @"SELECT DISTINCT fac.togetherflag,sc.rbtogetherflag,sc.rbcontainertype FROM containersubcontainer cc
            LEFT JOIN containercurrentinfo fac ON fac.containerid=cc.containerid--父卡
            LEFT JOIN container sc ON sc.containerid=cc.subcontainerid--子卡
            WHERE  sc.rbtogetherflag='{0}' AND sc.rbcontainertype='{1}' and sc.status!=0 and fac.togetherflag not in ({2}) ";
            var validateInfo = DatabaseAccess.DBUtility.DatabaseHelper.Query_ReturnDatTable(string.Format(strSql,
                con["RBTOGETHERFLAG"].ToString(), con["RBCONTAINERTYPE"].ToString(), faTogetherFlags));
            if (validateInfo.Rows.Count > 0)
            {
                result.Result = false;
                result.Message = "热表批次号：" + con["RBTOGETHERFLAG"].ToString() + "重复，请更新批次号后创建";
                context.Response.Write(JsonConvert.SerializeObject(result));
                return;
            }
        }

        var containerBaseInfo = new ContainerStartInfo();
        var faContainerDt = m_CommonObj.GetTableInfo("container", "containerid", con["FATHERCONTAINERID"].ToString());

        var conFamily = m_RbContianer.GetContainerProductFamily(con["FATHERCONTAINERID"].ToString());
        containerBaseInfo.ChildList = null;

        //if (con["CONTAINERTYPE"].ToString() == "3")
        //{
        ////查询父卡的有效子序号信息
        //var exuteEntity = new ExcuteEntity("container", ExcuteEntity.ExcuteTypeEnum.selectAll);
        //exuteEntity.WhereFileds = new List<FieldEntity>() { new FieldEntity("parentcontainerid", con["FATHERCONTAINERID"].ToString(), FieldEntity.FieldTypeEnum.Str), new FieldEntity("status", "1", FieldEntity.FieldTypeEnum.Str) };
        //var tempChildt = DatabaseHelper.QueryDataByEntity(exuteEntity);
        ////获取最新的子序号信息
        //var maxNo = m_CommonObj.GetNewChildContainerNextIndex(con["TOGATHERFLAG"].ToString(), 3);

        ////子序号赋值
        //var childDt = new DataTable();
        //childDt.Columns.Add("ContainerName");
        //childDt.Columns.Add("Qty");
        //childDt.Columns.Add("ChildBeginStep");

        //for (var i = 0; i < tempChildt.Rows.Count; i++)
        //{
        //    maxNo++;
        //    var childRow = childDt.NewRow();
        //    childRow["ContainerName"] = con["TOGATHERFLAG"].ToString() + maxNo.ToString("D3");
        //    childRow["Qty"] = 1;
        //    childRow["ChildBeginStep"] = beginStep;

        //    childDt.Rows.Add(childRow);
        //}
        //containerBaseInfo.ChildList = childDt;
        //}
        //机型
        containerBaseInfo.MfgBatch = faContainerDt.Rows[0]["mfgbatch"].ToString();
        var listFamily = new Dictionary<int, String>();
        foreach (DataRow productfamily in conFamily.Rows)
        {
            listFamily.Add(int.Parse(productfamily["sequence"].ToString()), productfamily["productfamilyname"].ToString());
        }
        containerBaseInfo.MfgOrder = con["MFGORDERNAME"].ToString();
        containerBaseInfo.ProductFamilyList = listFamily;
        //containerBaseInfo
        m_RbContianer.FillContainerDefaultInfo(ref containerBaseInfo, m_UserInfo.FactoryID);
        containerBaseInfo.Qty = con["qty"].ToString();
        containerBaseInfo.ContainerName = con["CONTAINERNAME"].ToString();
        containerBaseInfo.IsSelfMfg = con["ISSELFMFG"].ToString();
        containerBaseInfo.TogetherFlag = con["TOGATHERFLAG"].ToString();
        containerBaseInfo.Factory = m_UserInfo.Factory;
        containerBaseInfo.CheckTechnique = "";//暂时为空
        containerBaseInfo.UOM = "件";//暂时指定
        containerBaseInfo.WorkCenter = con["WORKCENTER"].ToString();
        containerBaseInfo.Team = "";//暂时为空
        containerBaseInfo.StartEmployee = m_UserInfo.EmployeeName;
        containerBaseInfo.BeginStep = beginStep;
        containerBaseInfo.ProductName = con["PRODUCTNAME"].ToString();
        containerBaseInfo.ProductRevision = con["PRODUCTREVISION"].ToString();
        containerBaseInfo.ProductuseROR = false;
        containerBaseInfo.MfgWorkflowName = con["MFGWORKFLOWNAME"].ToString();
        containerBaseInfo.MfgWorkflowRevision = con["MFGWORKFLOWREVISION"].ToString();
        containerBaseInfo.WorkflowName = con["WORKFLOWNAME"].ToString();
        containerBaseInfo.WorkflowRevision = con["WORKFLOWREVISION"].ToString();
        containerBaseInfo.MfgWorkflowuseROR = false;
        containerBaseInfo.Comment = "";
        containerBaseInfo.PlannedStartDate = DateTime.Parse(con["PLANNEDSTARTDATE"].ToString()).ToString("yyyy-MM-ddTHH:mm:ss");
        containerBaseInfo.PlannedCompletionDate = DateTime.Parse(con["PLANNEDCOMPLETIONDATE"].ToString()).ToString("yyyy-MM-ddTHH:mm:ss");
        containerBaseInfo.ContainerType = con["CONTAINERTYPE"].ToString(); containerBaseInfo.RbContainerType = con["RBCONTAINERTYPE"].ToString();
        containerBaseInfo.RbTogetherflag = con["RBTOGETHERFLAG"].ToString();

        if (!m_RbContianer.IsExistsWorkflowDocInfo(containerBaseInfo.WorkflowName.ToString(), containerBaseInfo.WorkflowRevision.ToString()))
        {
            result.Result = false;
            result.Message = string.Format("子工艺：{0}-{1}工艺附件信息不全，无法开卡", containerBaseInfo.WorkflowName.ToString(), containerBaseInfo.WorkflowRevision.ToString());
            context.Response.Write(JsonConvert.SerializeObject(result));
            return;
        }

        if (!string.IsNullOrWhiteSpace(beginStep) && con["CONTAINERTYPE"].ToString() == "3") //如果是批量带子序号，添加对应子序号 add by zhangrj 2022-11-18
        {
            containerBaseInfo.Qty = childContainer.Rows.Count;
            //子序号赋值
            var childDt = new DataTable();
            childDt.Columns.Add("ContainerName");
            childDt.Columns.Add("Qty");
            childDt.Columns.Add("ChildBeginStep");
            childDt.Columns.Add("TogetherFlag");
            childDt.Columns.Add("QualificationNum");
            childDt.Columns.Add("RbContainerType");
            foreach (DataRow item in childContainer.Rows)
            {
                if (string.IsNullOrWhiteSpace(item["qualificationnum"].ToString()))
                {
                    result.Result = false;
                    result.Message = "主卡子序号不存在";
                    break;
                }
                var childRow = childDt.NewRow();
                childRow["ContainerName"] = containerBaseInfo.ContainerName + item["qualificationnum"].ToString();
                childRow["Qty"] = 1;
                childRow["ChildBeginStep"] = beginStep;
                childRow["TogetherFlag"] = containerBaseInfo.TogetherFlag;
                childRow["QualificationNum"] = item["qualificationnum"].ToString();
                childRow["RbContainerType"] = containerBaseInfo.RbContainerType;
                childDt.Rows.Add(childRow);
            }
            containerBaseInfo.ChildList = childDt;
        }
        else if (!string.IsNullOrWhiteSpace(beginStep) && con["CONTAINERTYPE"].ToString() == "7") //如果主卡是单件单卡，将单件单卡转为批量子序号 add by zhangrj 2022-11-18
        {
            containerBaseInfo.ContainerType = "3";//将热表开卡批次改为批量带子序号
            //子序号赋值
            var childDt = new DataTable();
            childDt.Columns.Add("ContainerName");
            childDt.Columns.Add("Qty");
            childDt.Columns.Add("ChildBeginStep");
            childDt.Columns.Add("TogetherFlag");
            childDt.Columns.Add("QualificationNum");
            childDt.Columns.Add("RbContainerType");
            if (containers.Rows.Count == 1) //单个单件卡开卡，单独处理，可以解决多个单卡子序号问题数据
            {
                DataTable dtfacontainer = m_CommonObj.GetTableInfo("container", "containerid", containers.Rows[0]["FATHERCONTAINERID"].ToString());
                string qualificationnum = dtfacontainer.Rows[0]["qualificationnum"].ToString();
                if (string.IsNullOrWhiteSpace(qualificationnum) && dtfacontainer.Rows[0]["togetherflag"].ToString() == dtfacontainer.Rows[0]["containername"].ToString())
                {
                    containerBaseInfo.ContainerType = "2";
                }
                else if (string.IsNullOrWhiteSpace(qualificationnum))
                {
                    result.Result = false;
                    result.Message = "主卡子序号不存在";
                }
                else
                {
                    DataRow childRow = childDt.NewRow();
                    childRow["ContainerName"] = containerBaseInfo.ContainerName + qualificationnum;
                    childRow["Qty"] = 1;
                    childRow["ChildBeginStep"] = beginStep;
                    childRow["TogetherFlag"] = containerBaseInfo.TogetherFlag;
                    childRow["QualificationNum"] = qualificationnum;
                    childRow["RbContainerType"] = containerBaseInfo.RbContainerType;
                    childDt.Rows.Add(childRow);
                    containerBaseInfo.ChildList = childDt;
                }
            }
            else
            {
                foreach (DataRow item in containers.Rows)
                {
                    string qualificationnum = m_CommonObj.GetTableInfo("container", "containerid", item["FATHERCONTAINERID"].ToString()).Rows[0]["qualificationnum"].ToString();
                    if (string.IsNullOrWhiteSpace(qualificationnum))
                    {
                        result.Result = false;
                        result.Message = "主卡子序号不存在";
                        break;
                    }
                    DataRow childRow = childDt.NewRow();
                    childRow["ContainerName"] = containerBaseInfo.ContainerName + qualificationnum;
                    childRow["Qty"] = 1;
                    childRow["ChildBeginStep"] = beginStep;
                    childRow["TogetherFlag"] = containerBaseInfo.TogetherFlag;
                    childRow["QualificationNum"] = qualificationnum;
                    childRow["RbContainerType"] = containerBaseInfo.RbContainerType;
                    childDt.Rows.Add(childRow);
                }
                containerBaseInfo.ChildList = childDt;
            }
        }
        else
        {
            containerBaseInfo.ContainerType = "2";
        }
        if (!result.Result)
        {
            context.Response.Write(JsonConvert.SerializeObject(result));
            return;
        }
        //如果最终批次为批量加工，清空子序号列表
        if (containerBaseInfo.ContainerType.ToString() == "2")
        {
            containerBaseInfo.ChildList = null;
        }

        var serverInfo = new ServerHostInfo();
        serverInfo.UserName = m_UserInfo.APIUserName;
        serverInfo.Password = m_UserInfo.APIPassword;
        containerBaseInfo.ServerHostInfo = serverInfo;
        //增加批次属性
        AddContainerAttribute(containerBaseInfo, con);
        //api创建
        var tempResult = m_ContainerObj.StartContainer(containerBaseInfo);

        //获取下批次关联的工艺信息
        var subWorkflowDt = m_CommonObj.GetWorkflowInfoByNameAndRev(new Dictionary<string, string>() { 
            {"Rev",containerBaseInfo .MfgWorkflowRevision.ToString() },
            {"WorkflowName",containerBaseInfo.MfgWorkflowName.ToString()}
        });
        var subWorkflowId = subWorkflowDt.Rows[0]["workflowid"].ToString();
        var subProcessNo = subWorkflowDt.Rows[0]["process_no"].ToString();
        //存储主子映射信息
        if (!tempResult.IsError)
        {
            string subContainerId = m_CommonObj.GetTableInfo("container", "containername", containerBaseInfo.ContainerName.ToString()).Rows[0]["containerid"].ToString();
            var exuteEntitys = new List<ExcuteEntity>();
            if (childContainer.Rows.Count > 0) //批量带子序号
            {
                foreach (DataRow dr in containers.Rows)
                {
                    foreach (DataRow item in childContainer.Rows)
                    {
                        var exuteEntity = new ExcuteEntity("containersubcontainer", ExcuteEntity.ExcuteTypeEnum.insert);
                        exuteEntity.ExcuteFileds = new List<FieldEntity>() {new FieldEntity("containerid", dr["FATHERCONTAINERID"].ToString(), FieldEntity.FieldTypeEnum.Str),
                                                                          new FieldEntity("workflowstepid",dr["FAWORKFLOWSTEPID"].ToString(), FieldEntity.FieldTypeEnum.Str),
                                                                          new FieldEntity("containersubcontainerid", Guid.NewGuid().ToString(), FieldEntity.FieldTypeEnum.Str),
                                                                          new FieldEntity("createemployeeid", m_UserInfo.EmployeeID, FieldEntity.FieldTypeEnum.Str),
                                                                          new FieldEntity("faqty", dr["FAQTY"].ToString(), FieldEntity.FieldTypeEnum.Str),
                                                                          new FieldEntity("WorkflowStepName", dr["FAWORKFLOWSTEPNAME"].ToString() , FieldEntity.FieldTypeEnum.Str),
                                                                          new FieldEntity("SubWorkflowID", subWorkflowId, FieldEntity.FieldTypeEnum.Str),
                                                                          new FieldEntity("SubProcessNo",subProcessNo, FieldEntity.FieldTypeEnum.Str),
                                                                          new FieldEntity("createdate",DateTime.Now, FieldEntity.FieldTypeEnum.DateTime),
                                                                          new FieldEntity("subcontainerid", subContainerId, FieldEntity.FieldTypeEnum.Str),
                                                                          new FieldEntity("childcontainerid",item["CONTAINERID"].ToString(), FieldEntity.FieldTypeEnum.Str),
                                                                          new FieldEntity("isuse",0, FieldEntity.FieldTypeEnum.Numer )};
                        exuteEntitys.Add(exuteEntity);
                    }
                }
            }
            else
            {
                foreach (DataRow dr in containers.Rows)
                {
                    var exuteEntity = new ExcuteEntity("containersubcontainer", ExcuteEntity.ExcuteTypeEnum.insert);
                    exuteEntity.ExcuteFileds = new List<FieldEntity>() {new FieldEntity("containerid", dr["FATHERCONTAINERID"].ToString(), FieldEntity.FieldTypeEnum.Str),
                                                                          new FieldEntity("workflowstepid",dr["FAWORKFLOWSTEPID"].ToString(), FieldEntity.FieldTypeEnum.Str),
                                                                          new FieldEntity("containersubcontainerid", Guid.NewGuid().ToString(), FieldEntity.FieldTypeEnum.Str),
                                                                          new FieldEntity("createemployeeid", m_UserInfo.EmployeeID, FieldEntity.FieldTypeEnum.Str),
                                                                          new FieldEntity("faqty", dr["FAQTY"].ToString(), FieldEntity.FieldTypeEnum.Str),
                                                                          new FieldEntity("WorkflowStepName", dr["FAWORKFLOWSTEPNAME"].ToString() , FieldEntity.FieldTypeEnum.Str),
                                                                          new FieldEntity("SubWorkflowID", subWorkflowId, FieldEntity.FieldTypeEnum.Str),
                                                                          new FieldEntity("SubProcessNo",subProcessNo, FieldEntity.FieldTypeEnum.Str),
                                                                          new FieldEntity("createdate",DateTime.Now, FieldEntity.FieldTypeEnum.DateTime),
                                                                          new FieldEntity("subcontainerid", subContainerId, FieldEntity.FieldTypeEnum.Str),
                                                                          new FieldEntity("isuse",0, FieldEntity.FieldTypeEnum.Numer )};

                    exuteEntitys.Add(exuteEntity);
                }
            }
            DatabaseHelper.ExecuteDataByEntitys(exuteEntitys);
            //添加批次新属性表
            m_RbContianer.SaveMainContainerNewAttribute(con["FATHERCONTAINERID"].ToString(), containerBaseInfo.ContainerName.ToString(), con["FAWORKFLOWSTEPID"].ToString());
            //m_RbContianer.SaveContainerApsPoolInfo(containerBaseInfo.ContainerName.ToString(),containerBaseInfo.WorkCenter.ToString());
            result.Result = true;
            result.Message = "创建成功";
        }
        else
        {
            result.Result = false;
            result.Message = tempResult.Message;
        }

        context.Response.Write(JsonConvert.SerializeObject(result));

    }
    /// <summary>
    /// 添加批次属性
    /// </summary>
    /// <param name="containerBase"></param>
    /// <param name="con"></param>
    void AddContainerAttribute(ContainerStartInfo containerBase, DataRow con)
    {
        DataTable userattributedt = new DataTable();
        userattributedt.Columns.Add("Name");
        userattributedt.Columns.Add("Value");

        DataRow dr = userattributedt.NewRow();
        dr["Name"] = "CheckTechnique";
        dr["Value"] = containerBase.CheckTechnique;
        userattributedt.Rows.Add(dr);

        dr = userattributedt.NewRow();
        dr["Name"] = "BeginStep";
        dr["Value"] = containerBase.BeginStep;
        userattributedt.Rows.Add(dr);

        dr = userattributedt.NewRow();
        dr["Name"] = "热表时效性";
        dr["Value"] = con["IsTimeEffective"].ToString();
        userattributedt.Rows.Add(dr);

        /*-----工艺确认流程------*/
        string sql = string.Format(@"SELECT c.containerid,wf.workflowtype2 FROM workflow wf
                        LEFT JOIN Workflowbase wfb ON wfb.workflowbaseid = wf.workflowbaseid
                        LEFT JOIN container c ON c.mfgworkflowid = wf.workflowid AND c.status = 1
                        WHERE wfb.workflowname = '{0}' AND wf.workflowrevision = '{1}'", containerBase.MfgWorkflowName, containerBase.MfgWorkflowRevision);
        DataTable dtWorkflow = DatabaseHelper.Query_ReturnDatTable(sql);
        if (dtWorkflow.Rows.Count > 0) //理论上不会为空，但是还是做判断
        {
            //该工艺不存在任何批次，或者工艺类型是临时工艺的，都要走工艺确认流程
            if (string.IsNullOrWhiteSpace(dtWorkflow.Rows[0]["containerid"].ToString()) || dtWorkflow.Rows[0]["workflowtype2"].ToString().Trim() == "临时工艺")
            {
                DataTable levelAttributes = m_CommonObj.GetFatoryAttributes(m_UserInfo.FactoryID);
                DataRow[] datarows = levelAttributes.Select("USERATTRIBUTENAME='工艺确认流程'");
                if (datarows.Length > 0)
                {
                    string[] strWorkflows = datarows[0]["ATTRIBUTEVALUE"].ToString().Split('：');
                    containerBase.WorkflowName = strWorkflows.First();
                    containerBase.WorkflowRevision = strWorkflows.Last();
                }
                dr = userattributedt.NewRow();
                dr["Name"] = "工艺确认";
                dr["Value"] = "";
                userattributedt.Rows.Add(dr);
            }
        }
        /*-----------------------*/
        if (containerBase.MonthPlan != null && !String.IsNullOrWhiteSpace(containerBase.MonthPlan.ToString()))
        {
            dr = userattributedt.NewRow();
            dr["Name"] = "monthPlanName";
            dr["Value"] = containerBase.MonthPlan;
            userattributedt.Rows.Add(dr);
        }

        //if (containerBase.IsSelfMfg == "0")
        //{
        //    dr = userattributedt.NewRow();
        //    dr["Name"] = "材料牌号";
        //    dr["Value"] = "";
        //    userattributedt.Rows.Add(dr);

        //    dr = userattributedt.NewRow();
        //    dr["Name"] = "实发数/顺序号";
        //    dr["Value"] = "";
        //    userattributedt.Rows.Add(dr);

        //    dr = userattributedt.NewRow();
        //    dr["Name"] = "熔炉号母";
        //    dr["Value"] = "";
        //    userattributedt.Rows.Add(dr);

        //    dr = userattributedt.NewRow();
        //    dr["Name"] = "检验编号";
        //    dr["Value"] = "";
        //    userattributedt.Rows.Add(dr);

        //    dr = userattributedt.NewRow();
        //    dr["Name"] = "库房保管";
        //    dr["Value"] = "";
        //    userattributedt.Rows.Add(dr);

        //    dr = userattributedt.NewRow();
        //    dr["Name"] = "器材检验";
        //    dr["Value"] = "";
        //    userattributedt.Rows.Add(dr);

        //    dr = userattributedt.NewRow();
        //    dr["Name"] = "代料牌号";
        //    dr["Value"] = "";
        //    userattributedt.Rows.Add(dr);

        //    dr = userattributedt.NewRow();
        //    dr["Name"] = "代料规格";
        //    dr["Value"] = "";
        //    userattributedt.Rows.Add(dr);

        //    dr = userattributedt.NewRow();
        //    dr["Name"] = "代料单号";
        //    dr["Value"] = "";
        //    userattributedt.Rows.Add(dr);

        //    dr = userattributedt.NewRow();
        //    dr["Name"] = "平行作业单号";
        //    dr["Value"] = "";
        //    userattributedt.Rows.Add(dr);

        //    dr = userattributedt.NewRow();
        //    dr["Name"] = "平行作业工序";
        //    dr["Value"] = "";
        //    userattributedt.Rows.Add(dr);

        //    dr = userattributedt.NewRow();
        //    dr["Name"] = "顾客代表";
        //    dr["Value"] = "";
        //    userattributedt.Rows.Add(dr);
        //}

        userattributedt.AcceptChanges();
        containerBase.AttributeList = userattributedt;

    }

    /// <summary>
    /// 获取热表最新批次号,获取containername和rbTogetherflag
    /// </summary>
    /// <param name="context"></param>
    public void GetNewestContainerNo(HttpContext context)
    {
        context.Response.ContentType = "text/plain";
        uMESProcessResult result = new uMESProcessResult();
        result.Result = false;
        var returnData = new Dictionary<string, string>();

        var prefixInfo = context.Request["prefixInfo"].ToString();//前缀信息
        var rbTogetherflag = context.Request["rbTogetherflag"].ToString();//热表大批次信息

        if (string.IsNullOrWhiteSpace(prefixInfo))
        {
            result.Message = "没有传入参数";
            context.Response.Write(JsonConvert.SerializeObject(result));
            return;
        }
        //查询此机加卡（父卡）的子和父togetherFlag
        string faTogetherFlags = "";
        var faTogetherFlagDt = m_RbContianer.GetRelativesFatogetherflag(context.Request["faTogetherFlag"].ToString());
        foreach (DataRow r in faTogetherFlagDt.Rows)
        {
            faTogetherFlags += "'" + r["faTogetherFlag"].ToString() + "',";
        }
        faTogetherFlags = faTogetherFlags.TrimEnd(',');
        //查询机加大批次号和热表类型对应的热表大批次号
        var maxIndex = 0;
        var subContainerDt = m_RbContianer.GetSubContainer(new Dictionary<string, string>() { { "FaTogetherFlags", faTogetherFlags}, 
        { "SubRbContainerType", context.Request["subRbContainerType"].ToString() } });
        if (subContainerDt.Rows.Count > 0)
        {
            returnData["RbTogetherflag"] = subContainerDt.Rows[0]["RbTogetherflag"].ToString();
            returnData["RbTogetherflagType"] = "1";//标记为历史大批次号
        }
        else
        {
            maxIndex = m_RbContianer.GetNewestRbTogetherflag(rbTogetherflag);
            returnData["RbTogetherflag"] = rbTogetherflag + (++maxIndex).ToString("D4");
            returnData["RbTogetherflagType"] = "0";//标记为最新的大批次号
        }
        //查询最大批次号
        maxIndex = m_RbContianer.GetNewestContainerNo(prefixInfo + returnData["RbTogetherflag"] + "-");
        returnData["RbContainerNo"] = returnData["RbTogetherflag"] + "-" + (++maxIndex).ToString("D2");

        result.Result = true;
        result.ReturnData = returnData;
        context.Response.Write(JsonConvert.SerializeObject(result));
    }
    /// <summary>
    /// 获取热表最新批次号,只获取containername
    /// </summary>
    /// <param name="context"></param>
    public void GetNewestContainerNo2(HttpContext context)
    {
        context.Response.ContentType = "text/plain";
        uMESProcessResult result = new uMESProcessResult();
        result.Result = false;

        var prefixInfo = context.Request["prefixInfo"].ToString();//前缀信息
        var rbTogetherflag = context.Request["rbTogetherflag"].ToString();
        //查询最大批次号
        var maxIndex = m_RbContianer.GetNewestContainerNo(prefixInfo + rbTogetherflag + "-");
        result.ReturnData = rbTogetherflag + "-" + (++maxIndex).ToString("D2");

        result.Result = true;
        context.Response.Write(JsonConvert.SerializeObject(result));
    }
    /// <summary>
    /// 获取已经创建的热表批次
    /// </summary>
    /// <param name="context"></param>
    public void GetCreatedRbContianer(HttpContext context)
    {
        context.Response.ContentType = "text/plain";
        var popUpdata = new DataTable();
        uMESProcessResult result = new uMESProcessResult();
        result.Result = false;

        if (context.Request["containers"] == null)
        {
            result.Message = "无批次信息";
            context.Response.Write(JsonConvert.SerializeObject(result));
            return;
        }

        var containers = JsonConvert.DeserializeObject<DataTable>(context.Request["containers"]);

        //查询已经创建的热表批次
        var para = new Dictionary<string, string>() { { "SubContainerFactoryID", m_UserInfo.FactoryID }, { "ContainerIDs", "" } };
        foreach (DataRow dr in containers.Rows)
        {
            para["ContainerIDs"] += "'" + dr["ContainerID"].ToString() + "',";
        }
        if (!string.IsNullOrWhiteSpace(para["ContainerIDs"]))
        {
            para["ContainerIDs"] = para["ContainerIDs"].TrimEnd(',');
        }

        DataTable subContainer = m_RbContianer.GetSubContainer(para);
        foreach (DataColumn dr in subContainer.Columns)
        {
            dr.ColumnName = dr.ColumnName.ToUpper();
        }

        subContainer = subContainer.DefaultView.ToTable(true, "CONTAINERNAME", "QTY", "WORKFLOWSTEPNAME", "CONTAINERID");

        result.Result = true;
        result.DBTable = subContainer;

        context.Response.Write(JsonConvert.SerializeObject(result));
    }

    /// <summary>
    /// 初始化页面
    /// </summary>
    /// <param name="context"></param>
    public void IntiPageData(HttpContext context)
    {
        context.Response.ContentType = "text/plain";
        var popUpdata = new DataTable();
        uMESProcessResult result = new uMESProcessResult();
        result.Result = false;
        Dictionary<string, object> returnData = new Dictionary<string, object>();
        returnData.Add("SubWorkflowId", "");
        returnData.Add("SubWorkflowInfo", "");
        returnData.Add("SubProductInfo", "");
        returnData.Add("EstimatedCompleteDate", ""); //转工预计完成时间  
        returnData.Add("ToWorkcenterID", ""); //转工接收工区        

        if (context.Session["PopupData"] == null)//检查获取的弹出缓存数据
        {
            result.Message = "未检测到弹出数据缓存";
            context.Response.Write(JsonConvert.SerializeObject(result));
            return;
        }
        popUpdata = context.Session["PopupData"] as DataTable;
        popUpdata.TableName = "MainContainer";

        //如果是批量带子序号，带出子序号列表 add by zhangrj 2022-10-27
        DataTable dtChildContainer = new DataTable();

        //查询已经创建的热表批次
        var para = new Dictionary<string, string>() { { "SubContainerFactoryID", m_UserInfo.FactoryID }, { "ContainerIDs", "" } };
        foreach (DataRow dr in popUpdata.Rows)
        {
            para["ContainerIDs"] += "'" + dr["ContainerID"].ToString() + "',";
        }
        if (!string.IsNullOrWhiteSpace(para["ContainerIDs"]))
        {
            para["ContainerIDs"] = para["ContainerIDs"].TrimEnd(',');
        }

        DataTable subContainer = m_RbContianer.GetSubContainer(para);
        subContainer.TableName = "SubContainer";
        subContainer = subContainer.DefaultView.ToTable(true, "CONTAINERNAME", "QTY", "WORKFLOWSTEPNAME", "CONTAINERID");

        //工区信息
        DataTable workcenterDt = m_CommonObj.GetWorkCenterByFacoryID(m_UserInfo.FactoryID, false);
        workcenterDt.TableName = "WorkCenter";
        DataTable shipStepDt = new DataTable();
        //查询机加工序的子工艺信息（热表工艺）
        DataTable subWorkflowDt = new DataTable();
        if (popUpdata.Columns.Contains("containershiprecordid"))
        {
            string workflowStepID = popUpdata.Rows[0]["WorkflowStepID"].ToString();
            if (popUpdata.Rows[0]["ContainerType"].ToString() == "3")
            {
                dtChildContainer = m_RbContianer.GetChildContainer(popUpdata.Rows[0]["ContainerID"].ToString(), workflowStepID);
                dtChildContainer.TableName = "ChildContainer";
            }
            //查询机加工序的子工艺信息（热表工艺）
            subWorkflowDt = m_CommonObj.GetSubWorkflowInfo(new Dictionary<string, string> { { "WorkflowStepID", workflowStepID }, { "FactoryID", m_UserInfo.FactoryID } });
            //获取已经接收的工区信息
            DataTable shipDt = m_CommonObj.GetTableInfo("containershiprecord", "containershiprecordid", popUpdata.Rows[0]["containershiprecordid"].ToString());
            returnData["EstimatedCompleteDate"] = shipDt.Rows[0]["EstimatedCompleteDate"].ToString();
            returnData["ToWorkcenterID"] = shipDt.Rows[0]["ToWorkcenterID"].ToString();
            //转工工序信息
            var shipID = popUpdata.Rows[0]["containershiprecordid"].ToString();
            shipStepDt = m_RbContianer.GetShipStepsByID(shipID);

            returnData.Add("StepPlannedStartDate", GetStepPlannedStartDate(popUpdata.Rows[0]["ContainerID"].ToString(), workflowStepID));
        }
        else
        {
            DataTable dt = context.Session["PopupStepData"] as DataTable;
            if (popUpdata.Rows[0]["ContainerType"].ToString() == "3")
            {
                dtChildContainer = m_RbContianer.GetChildContainer(popUpdata.Rows[0]["ContainerID"].ToString(), dt.Rows[0]["SHIPSTEPID"].ToString());
                dtChildContainer.TableName = "ChildContainer";
            }
            //查询机加工序的子工艺信息（热表工艺）
            subWorkflowDt = m_CommonObj.GetSubWorkflowInfo(new Dictionary<string, string> { { "WorkflowStepID", dt.Rows[0]["SHIPSTEPID"].ToString() }, { "FactoryID", m_UserInfo.FactoryID } });
            returnData["EstimatedCompleteDate"] = "";
            returnData["ToWorkcenterID"] = "";
            shipStepDt.Columns.Add("WORKFLOWSTEPID");
            shipStepDt.Columns.Add("WORKFLOWSTEPNAME");
            //转工工序信息
            foreach (DataRow item in dt.Rows)
            {
                DataRow dr = shipStepDt.NewRow();
                dr["WORKFLOWSTEPID"] = item["SHIPSTEPID"].ToString();
                dr["WORKFLOWSTEPNAME"] = item["SHIPSTEPNAME"].ToString();
                shipStepDt.Rows.Add(dr);
            }
            //
            returnData.Add("StepPlannedStartDate", GetStepPlannedStartDate(popUpdata.Rows[0]["ContainerID"].ToString(), dt.Rows[0]["SHIPSTEPID"].ToString()));
        }
        shipStepDt.TableName = "ShipStepDt";
        //处理机加工序的子工艺信息（热表工艺）
        if (subWorkflowDt.Rows.Count > 0)
        {
            returnData["SubWorkflowId"] = subWorkflowDt.Rows[0]["subworkflowid"].ToString();
            returnData["SubWorkflowInfo"] = subWorkflowDt.Rows[0]["subworkflowname"].ToString() + ":" + subWorkflowDt.Rows[0]["subworkflowrevision"].ToString();
            DataTable subProductDt = m_CommonObj.GetProductInfoByID(subWorkflowDt.Rows[0]["subproductid"].ToString());
            if (subProductDt.Rows.Count > 0)
            {
                returnData["SubProductInfo"] = subProductDt.Rows[0]["PRODUCTNAME"].ToString() + ":" + subProductDt.Rows[0]["productrevision"].ToString();
            }

            //查询子工艺关联的子件号,可能一对多，系统处理，和主件号匹配 add:Wangjh 2023/2/20
            subProductDt = DatabaseHelper.Query_ReturnDatTable(string.Format(@"select pw.workflowid,pb.productname,p.productrevision from productworkflowmapping pw
left join product p on p.productid=pw.productid
left join productbase pb on pb.productbaseid=p.productbaseid
where pw.workflowid='{0}'", subWorkflowDt.Rows[0]["subworkflowid"].ToString()));
            if (subProductDt.Rows.Count > 0)
            {
                var subProduct = subProductDt.Select("productname like '" + popUpdata.Rows[0]["productname"].ToString() + "%'");
                if (subProduct.Length > 0)
                {
                    returnData["SubProductInfo"] = subProduct[0]["PRODUCTNAME"].ToString() + ":" + subProduct[0]["productrevision"].ToString();
                }

            }
            //查询子工艺最新的工艺 add:Wangjh 20230322
            var newestSubWorkflow = m_CommonObj.GetWorkflowInfoByNameAndRev(new Dictionary<string, string>(){
                {"WorkflowName",subWorkflowDt.Rows[0]["subworkflowname"].ToString()}
            }).AsEnumerable().OrderByDescending(row => row["workflowid"].ToString()).FirstOrDefault();

            returnData["NewestSubWorkflowRev"] = newestSubWorkflow["workflowrevision"].ToString();
        }
        //DataSet resultSet = new DataSet();
        //格式化列名
        foreach (DataColumn dr in popUpdata.Columns)
        {
            dr.ColumnName = dr.ColumnName.ToUpper();
        }
        foreach (DataColumn dr in subContainer.Columns)
        {
            dr.ColumnName = dr.ColumnName.ToUpper();
        }
        foreach (DataColumn dr in workcenterDt.Columns)
        {
            dr.ColumnName = dr.ColumnName.ToUpper();
        }
        foreach (DataColumn dr in shipStepDt.Columns)
        {
            dr.ColumnName = dr.ColumnName.ToUpper();
        }

        returnData.Add(popUpdata.TableName, popUpdata);
        returnData.Add(subContainer.TableName, subContainer);
        returnData.Add(dtChildContainer.TableName, dtChildContainer);
        returnData.Add(workcenterDt.TableName, workcenterDt);
        returnData.Add(shipStepDt.TableName, shipStepDt);

        result.ReturnData = returnData;
        result.Result = true;
        context.Response.Write(JsonConvert.SerializeObject(result));
    }

    public string GetStepPlannedStartDate(string containerId, string workflowstepId)
    {
        try
        {
            string sql = string.Format("SELECT csp.plannedstartdate FROM containerstepplan csp WHERE csp.containerid = '{0}' AND csp.workflowstepid = '{1}'", containerId, workflowstepId);
            DataTable dt = DatabaseHelper.Query_ReturnDatTable(sql);
            if (dt.Rows.Count > 0 && !string.IsNullOrWhiteSpace(dt.Rows[0]["plannedstartdate"].ToString()))
            {
                return DateTime.Parse(dt.Rows[0]["plannedstartdate"].ToString()).AddDays(1).ToString("yyyy-MM-dd");
            }
            return DateTime.Now.ToString("yyyy-MM-dd");
        }
        catch
        {
            return DateTime.Now.ToString("yyyy-MM-dd");
        }
    }

}